package main

import (
	"io/ioutil"
	"fmt"
	"encoding/json"
	"sync"
	"strings"
	"time"
)

type CoinEggMarkets struct{
	Market []string
}

var (
	configFile = "config/coinEgg.json"
)

func CoinEggMarketsToRedis(inWg *sync.WaitGroup) error{
	defer inWg.Done()

	var markets CoinEggMarkets

	t := time.Now()

	// fmt.Printf("CoinEggMarketsToRedis begin.\n")

	file, err := ioutil.ReadFile(configFile)
	if err != nil {
		fmt.Printf("Error: %s\n", err)
		return err
	}

	dataJson := []byte(file)
	// fmt.Printf("%s\n", dataJson)

	err = json.Unmarshal(dataJson, &markets)
	if err != nil{
		fmt.Printf("Error: %s\n", err)
		return err
	}

	var wg sync.WaitGroup

	for v := range markets.Market{
		wg.Add(1)
		// fmt.Printf("CoinEggMarketToRedis(%s) begin.\n", markets.Market[v])
		go CoinEggMarketToRedis(markets.Market[v], &wg)
	}

	wg.Wait()

	fmt.Printf("CoinEggMarketsToRedis duration: %s.\n", time.Now().Sub(t))

	return nil
}

func CoinEggMarketToRedis(name string, wg *sync.WaitGroup){
	defer wg.Done()

	url := "https://api.coinegg.com/api/v1/ticker?coin=" + strings.ToLower(name)

	body := httpGet(url)

	key := "CoinEgg_" + name + "_BTC_Latest"

	err := client.Set(key, body, 0).Err()
	if err != nil {
		fmt.Printf("Error: %s\n", err)
	}else{
		// fmt.Printf("Success write: %s\n", key)
	}
	
}
